import { defineStore } from "pinia";
import { ref, computed } from "vue";
import type { User, LoginForm, LoginResponseData } from "@/types";
import {
  login as loginApi,
  getUserInfo,
  logout as logoutApi,
} from "@/api/auth";
import {
  getAccessToken,
  setAccessToken,
  setRefreshToken,
  setAccessTokenExpires,
  setRefreshTokenExpires,
  getUser,
  setUser,
  getPermissions,
  setPermissions,
  clearAuth,
  saveLoginInfo,
} from "@/utils/auth";
import { encryptPassword } from "@/utils/crypto";
import router from "@/router";
import { $getUserDetail } from "@/api/user";
import { getFirstAvailablePage } from "@/utils/permissions";

export const useAuthStore = defineStore("auth", () => {
  // 状态
  const token = ref<string | null>(getAccessToken());
  const user = ref<User | null>(getUser());
  const permissions = ref<string[]>(getPermissions());
  const loading = ref(false);

  // 计算属性
  const isLoggedIn = computed(() => !!token.value);
  const isAdmin = computed(() => user.value?.id ===1);
  const userRole = computed(() => user.value?.role || "");
  const userName = computed(
    () => user.value?.name || user.value?.username || ""
  );

  /**
   * 登录
   */
  const login = async (loginForm: LoginForm): Promise<void> => {
    try {
      loading.value = true;

      // 加密密码
      const encryptedPassword = encryptPassword(loginForm.password);

      // 调用实际登录API
      const response = await loginApi({
        loginName: loginForm.name,
        loginPassword: encryptedPassword,
        name: "",
        password: "",
      });

      // 保存认证信息
      const loginData: LoginResponseData = response.data;
      token.value = loginData.accessToken;




      // 根据页面权限设置权限数组
      const permissionList: string[] = [];
      if (loginData.roleFuncPrivilege.pagePrivilege === -1) {
        // -1表示拥有所有权限
        permissionList.push("*");
      } else {
        // 根据权限码解析具体权限
        const pagePrivilege = loginData.roleFuncPrivilege.pagePrivilege;
        if (pagePrivilege & 1) permissionList.push("preview");
        if (pagePrivilege & 2) permissionList.push("map");
        if (pagePrivilege & 4) permissionList.push("camera-set");
        if (pagePrivilege & 8) permissionList.push("video-replay");
        if (pagePrivilege & 16) permissionList.push("page");
        if (pagePrivilege & 32) permissionList.push("org");
        if (pagePrivilege & 64) permissionList.push("role");
        if (pagePrivilege & 128) permissionList.push("nvr");
        if (pagePrivilege & 256) permissionList.push("nmc");
        if (pagePrivilege & 512) permissionList.push("user");
        if (pagePrivilege & 1024) permissionList.push("alarm");
      }
      permissions.value = permissionList;

      // 保存所有token信息
      setAccessToken(loginData.accessToken);
      setRefreshToken(loginData.refreshToken);
      setAccessTokenExpires(loginData.accessTokenExpires);
      setRefreshTokenExpires(loginData.refreshTokenExpires);

      const userDetail = await $getUserDetail(parseInt(response.data.id))
      // 设置用户信息
      const userData: User = {
        id: loginData.id,
        name: loginData.name,
        username: loginData.name,
        role: loginData.userRoleInfo.name,
        eMail: userDetail.data.eMail,
        avatar: userDetail.data.avatar,
        pagePrivilege: loginData.roleFuncPrivilege.pagePrivilege,
        subPagePrivilege: loginData.roleFuncPrivilege.subPagePrivilege,
        nmcPrivilegeIds: loginData.roleFuncPrivilege.nmcPrivilegeIds,
      };
      user.value = userData;
      setUser(user.value);
      setPermissions(permissions.value);

      // 处理记住我功能
      if (loginForm.remember) {
        saveLoginInfo(loginForm.name, loginForm.password, true);
      } else {
        saveLoginInfo(loginForm.name, loginForm.password, false);
      }

      // 根据用户权限跳转到第一个有权限的页面
      const firstAvailablePage = getFirstAvailablePage(userData.pagePrivilege || 0);
      router.push(firstAvailablePage);
    } catch (error) {
      console.error("Login failed:", error);
      throw error;
    } finally {
      loading.value = false;
    }
  };

  /**
   * 获取用户信息
   */
  const fetchUserInfo = async (): Promise<void> => {
    try {
      if (!token.value) return;

      // 如果已有用户信息且权限为最高权限，无需重新获取
      if (user.value && permissions.value.includes("*")) {
        return;
      }

      // 调用实际API获取用户信息
      const response = await getUserInfo();

      // 处理用户信息
      const userData = response.data;
      if (!userData.pagePrivilege) {
        userData.pagePrivilege = -1; // 默认拥有所有页面权限
      }

      user.value = userData;

      // 根据页面权限设置权限数组
      const permissionList: string[] = [];
      if (userData.pagePrivilege === -1) {
        // -1表示拥有所有权限
        permissionList.push("*");
      } else {
        // 根据权限码解析具体权限
        const pagePrivilege = userData.pagePrivilege;
        if (pagePrivilege & 1) permissionList.push("preview");
        if (pagePrivilege & 2) permissionList.push("map");
        if (pagePrivilege & 4) permissionList.push("camera-set");
        if (pagePrivilege & 8) permissionList.push("video-replay");
        if (pagePrivilege & 64) permissionList.push("role");
        if (pagePrivilege & 128) permissionList.push("nvr");
        if (pagePrivilege & 256) permissionList.push("nmc");
      }
      permissions.value = permissionList;

      setUser(userData);
      setPermissions(permissions.value);
    } catch (error) {
      console.error("Get user info failed:", error);
      // 如果获取用户信息失败，仍然保持最高权限
      // 只有在token无效时才清除认证信息
      if ((error as any)?.response?.status === 401) {
        logout();
        throw error;
      }
      // 其他错误不影响权限，使用默认最高权限
      permissions.value = ["*"];
      setPermissions(permissions.value);
    }
  };

  /**
   * 登出
   */
  const logout = async (): Promise<void> => {
    try {
      // 调用实际登出API
      await logoutApi();

      // 清除本地认证信息
      token.value = null;
      user.value = null;
      permissions.value = [];

      clearAuth();

      // 跳转到登录页
      router.push("/login");
    } catch (error) {
      console.error("Logout failed:", error);
      // 即使登出API失败，也要清除本地认证信息
      token.value = null;
      user.value = null;
      permissions.value = [];
      clearAuth();
      router.push("/login");
    }
  };

  /**
   * 检查权限
   */
  const hasPermission = (permission: string): boolean => {
    return (
      permissions.value.includes(permission) || permissions.value.includes("*")
    );
  };

  /**
   * 检查是否有任一权限
   */
  const hasAnyPermission = (perms: string[]): boolean => {
    return perms.some((permission) => hasPermission(permission));
  };

  /**
   * 检查是否有所有权限
   */
  const hasAllPermissions = (perms: string[]): boolean => {
    return perms.every((permission) => hasPermission(permission));
  };

  /**
   * 初始化认证状态
   */
  const initAuth = async (): Promise<void> => {
    if (token.value && !user.value) {
      try {
        await fetchUserInfo();
      } catch (error) {
        // 如果获取用户信息失败，清除认证信息
        logout();
      }
    }
  };

  return {
    // 状态
    token,
    user,
    permissions,
    loading,

    // 计算属性
    isLoggedIn,
    isAdmin,
    userRole,
    userName,

    // 方法
    login,
    logout,
    fetchUserInfo,
    hasPermission,
    hasAnyPermission,
    hasAllPermissions,
    initAuth,
  };
});
